package com.tpc.eb.utils;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HTTPClient {
    public static String sendHttpRequest(String url, String jsonPara, int waitTime)  {
        String result = "";
        CloseableHttpClient httpclient =
                HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpPost httppost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(waitTime)
                    .setSocketTimeout(waitTime)
                    .build();
            httppost.setConfig(requestConfig);
            ByteArrayEntity entity = new
                    ByteArrayEntity(jsonPara.getBytes(Consts.UTF_8));
            entity.setContentType("application/json");//text/plain
            httppost.setEntity(entity);
            response = httpclient.execute(httppost);
            int statusCode =
                    response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                httppost.abort();
                result = "HttpClient,error status code :" + statusCode;
//                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                // 返回字符串
                result = EntityUtils.toString(responseEntity,
                        "UTF-8");
//                System.out.println(result);
            }
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            result = "提交给服务器的请求，不符合 HTTP 协议：" + e.getMessage();
            e.printStackTrace();
//            throw new RuntimeException(result, e);
        } catch (IOException e) {
            result = "向服务器承保接口发起 http 请 求,执行 post 请求异常：" + e.getMessage();
            e.printStackTrace();
//            throw new RuntimeException(result, e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
